package com.zcsy.manage.web.news;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.commons.util.PoiUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.news.YellowPage;
import com.zcsy.manage.model.system.Dict;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.news.IYellowPageService;
import com.zcsy.manage.service.system.IDictService;
import com.zcsy.manage.web.common.LogUtils;
import com.zcsy.manage.web.tools.JExcelReport;

/**
 * @Title: YellowPageController.java
 * @Package： com.zcsy.manage.web.news
 * @Description: 便民黄页控制层管理类
 * @author liuying 1075817474@qq.com
 * @Copyright: 2015 武汉中财数元信息技术有限公司 All rights reserved.
 * @date 2016年3月29日
 * @version 1.0
 * @see JDK1.7.0_75
 * @since
 */
@Controller
@RequestMapping(value = "/yellowPage")
public class YellowPageController {

	@Autowired
	private IYellowPageService yellowPageService;

	@Autowired
	private ICellInfoService cellInfoService;

	@Autowired
	private IDictService dictService;
	
	/**
	 * @Description 分页获取数据列表<br>
	 * 
	 * @param pNo
	 *            起始页
	 * @param pageName
	 *            黄页名
	 * @param req
	 *            用户请求
	 * @return 跳转页面URL
	 * @author liuying 1075817474@qq.com
	 * @date 2016年3月29日
	 * @see
	 */
	@RequestMapping(value = "yellowPageList", method = RequestMethod.GET)
	public String yellowPageList(Model model, Integer pNo, Integer pSize, 
			String pageName, HttpServletRequest req) {

		if (pNo == null) {
			pNo = Constants.PAGE_NO;
		}

		Integer pageSize;
		if (pSize == null) {
			pageSize = Constants.PAGE_SIZE;
		} else {
			switch (pSize) {
				case 0: pageSize = Constants.PAGE_SIZE;
				break;
				case 1: pageSize = Constants.PAGE_SIZE_TWENTY;
				break;
				case 2: pageSize = Constants.PAGE_SIZE_FIFTY;
				break;
				default:pageSize = Constants.PAGE_SIZE;
				break;
			}
		}
		
		// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
		PageHelper.startPage(pNo, pageSize);

		YellowPage yellowPage = new YellowPage();

		//获取当前小区id
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String cellId = user.getCurrentCell().getId();
		yellowPage.setCellId(cellId);

		// 黄页名不为空时，设置黄页名
		if (StringUtils.isNotEmpty(pageName)) {
			yellowPage.setPageName(pageName);
		}

		List<YellowPage> yellowPages = yellowPageService
				.selectByKeyword(yellowPage);
		PageInfo<YellowPage> info = new PageInfo<YellowPage>(yellowPages);

		model.addAttribute("yellowPage", info);
		model.addAttribute("currentPage", pNo);
		model.addAttribute("pSize", pSize);
		model.addAttribute("pageName", pageName);

		List<Dict> pageSizes = dictService.getDictFromCache("pageSize");
		model.addAttribute("pageSizes", pageSizes);

		return "news/yellowpage/yellowPageList";
	}

	/**
	 * @Description 编辑便民黄页<br>
	 * 
	 * @param id
	 *            主键id
	 * @return 跳转页面URL
	 * @author liuying 1075817474@qq.com
	 * @date 2016年3月29日
	 * @see
	 */
	@RequestMapping(value = "edityellowPage", method = RequestMethod.GET)
	public String edityellowPage(Model model, String id,HttpServletRequest req) {
		try {
			if (!String.valueOf(Constants.STATE_DISABLED).equals(id)) {
				YellowPage yellowPage = yellowPageService
						.selectByPrimaryKey(id);
				model.addAttribute("yellowPage", yellowPage);
				model.addAttribute("pagecellId", yellowPage.getCellId());
			} else {
			    User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		        String cellId = user.getCurrentCell().getId();
		        String cellName = user.getCurrentCell().getCellName();
		        YellowPage yellowPage = new YellowPage();
		        yellowPage.setCellId(cellId);
		        yellowPage.setCellName(cellName);
		        model.addAttribute("yellowPage", yellowPage);
			}
			
		} catch (Exception e) {
			return "error/404";
		}

		return "news/yellowpage/yellowPageEdit";
	}

	/**
	 * @Description 保存或更新便民黄页信息<br>
	 * 
	 * @param pageName
	 *            黄页名
	 * @param cellId
	 *            小区id
	 * @param phone0
	 *            电话1
	 * @param phone1
	 *            电话2
	 * @param addr
	 *            地址
	 * @param sort
	 *            排序
	 * @param pageId
	 *            页面id
	 * @param request
	 *            用户请求
	 * @param response
	 *            响应
	 * @return 请求结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年3月29日
	 * @see
	 */
	@RequestMapping(value = "saveOrUpdateYellowPage", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson saveYellowPage(String pageName, String cellId,
			String phone0, String phone1, String addr, Integer sort,
			String pageId, HttpServletRequest request,
			HttpServletResponse response) {
		RequestJson result = new RequestJson();
		User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		try {
			YellowPage record = new YellowPage();
			record.setPageName(pageName);
			record.setCellId(cellId);
			record.setPhone0(phone0);
			record.setPhone1(phone1);
			record.setAddr(addr);
			record.setSort(sort);
			if (pageId != null && !"".equals(pageId)) {
				record.setId(pageId);
				record.setUpdateTime(new Date());
				yellowPageService.update(record);
				LogUtils.insertLog("用户编辑便民黄页", user.getId(), request);

			} else {
				record.setId(UniqueNumberUtils.get18UniqueNumber());
				record.setSendTime(new Date());
				record.setUpdateTime(new Date());
				yellowPageService.insert(record);
				LogUtils.insertLog("用户新增便民黄页", user.getId(), request);

				// 插入一条区域，将当前区域所在的小区绑定依赖关系，有依赖的小区不能被删除
				CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
				cellInfo.setIsUsed(Constants.IS_USED);
				cellInfoService.update(cellInfo);
				
			}

		} catch (Exception e) {
			result.setSuccess(false);
		}

		return result;
	}

	/**
	 * @Description 根据多个id删除便民黄页信息<br>
	 * @param iDs
	 *            多个id
	 * @param req
	 *            用户请求
	 * @return 请求结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年3月29日
	 * @see
	 */
	@RequestMapping(value = "deletePage", method = RequestMethod.POST)
	@ResponseBody
	public RequestJson deletePage(String iDs, HttpServletRequest req) {

		RequestJson result = new RequestJson();
		User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);

		try {
			String ids[] = iDs.split("\\,");
			for (int i = 0; i < ids.length; i++) {
				yellowPageService.delete(ids[i]);
			}
			result.setSuccess(true);
			LogUtils.insertLog("用户删除便民黄页", user.getId(), req);

		} catch (NumberFormatException e) {
			result.setSuccess(false);
			result.setMsg("操作失败");
		}

		return result;
	}

	/**
	 * @Description 导出便民黄页信息<br>
	 * @param response
	 * @author fangli
	 * @date 2016年5月18日
	 * @see
	 */
	@RequestMapping("/exportYellowPageExcel")
	@ResponseBody
	public void exportYellowPageExcel(String pageName, HttpServletRequest request,
			HttpServletResponse response) {
		List<YellowPage> list;
		YellowPage record = new YellowPage();
		User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		String cellId = user.getCurrentCell().getId();
		
		// 标题不为空时，设置标题
		if (StringUtils.isNotEmpty(pageName)) {
			record.setPageName(pageName);
		}

		record.setCellId(cellId);

		try {
			// 得到导出的数据列表
			list = yellowPageService.selectByKeyword(record);

			// 将便民黄页对象转化为到处所需要的数据格式
			if (list.size() > 0) {
				ArrayList<ArrayList<String>> dataList = new ArrayList<ArrayList<String>>();
				int index = 1;
				for (YellowPage yellowPage : list) {
					ArrayList<String> temp = new ArrayList<String>();
					// 序号
					temp.add(String.valueOf(index++));
					temp.add(yellowPage.getPageName());
					temp.add(yellowPage.getCellName());
					temp.add(yellowPage.getPhone0());
					temp.add(yellowPage.getPhone1());
					temp.add(yellowPage.getAddr());
					dataList.add(temp);
				}
				// 导出标题列
				String[] rows = new String[] { "序号", "名称", "小区名", "电话号码1",
						"电话号码2", "地址" };
				// 导出excel文件每列宽度
				int[] style = new int[] { 5, 20, 20, 20, 20, 20 };
				// Excel文件sheet名称
				String sheetName = "便民黄页信息" + DateUtils.getCurrentDate();
				String fileName = "便民黄页信息";
				doExecl(response, fileName, sheetName, dataList, rows, style);
				LogUtils.insertLog("用户导出便民黄页清单", user.getId(), request);

			}
		} catch (Exception e) {
			return;
		}
	}

	/**
	 * @Description 通过传入的对象信息集合产生的excel表格<br>
	 * @param response
	 *            用户响应
	 * @param sheetName
	 *            excel表名称
	 * @param dataList
	 *            传入的数据列表
	 * @param rows
	 *            excel表的列控制，名称
	 * @param style
	 *            规定列宽等样式
	 * @throws Exception
	 * @author fangli
	 * @date 2016年5月18日
	 * @see
	 */
	private void doExecl(HttpServletResponse response, String tempName,
			String sheetName, ArrayList<ArrayList<String>> dataList,
			String[] rows, int[] style) throws Exception {
		// 输出的excel名称为中文，否则发生错误
		String tempFileName = tempName + ".xls";
		String fileName = new String(tempFileName.getBytes("GB2312"),
				"ISO_8859_1");

		ServletOutputStream fout = response.getOutputStream();
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-Disposition", "filename=" + fileName + "");
		JExcelReport jexcelOutStream = new JExcelReport();
		try {
			jexcelOutStream.excelreport(sheetName, dataList, rows, fout, style);
			fout.flush();
			fout.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Description 导入界面弹框
	 * @param cellId
	 *            小区id
	 * @return 跳转画面URL
	 * @author fangli
	 * @date 2016年5月18日
	 * @see
	 */
	@RequestMapping(value = "initList", method = RequestMethod.GET)
	public String initList(Model model, HttpServletRequest req) {
		//获取当前小区信息
        User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
		String cellId = user.getCurrentCell().getId();
		String url = "";
		try {
			CellInfo cellInfo = cellInfoService.selectByPrimaryKey(cellId);
			model.addAttribute("cellInfo",cellInfo);
			url = "news/yellowpage/initList";
		} catch (Exception e) {
			e.printStackTrace();
		}

		return url;
	}

	/**
	 * @Description 站点信息导入(直接导入站点的入口)<br>
	 * @param request
	 * @param response
	 * @return
	 * @author fangli
	 * @date 2016年5月19日
	 * @see
	 */
	@RequestMapping("/importYellowPage")
	@ResponseBody
	public RequestJson importYellowPage(@RequestParam("cellId") String cellId,
			HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html;charset=utf-8");
		RequestJson json = new RequestJson();
		final HttpSession session = request.getSession();
		User user = (User) session
				.getAttribute(RequestConstants.USER_SESSION_ID);
		String errorMsg = "";

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile imgFile = multipartRequest.getFile("fileIds");

		CommonsMultipartFile cf = (CommonsMultipartFile) imgFile;
		DiskFileItem fi = (DiskFileItem) cf.getFileItem();
		File f = fi.getStoreLocation();

		String fileNames = imgFile.getOriginalFilename();
		long fileSize = imgFile.getSize();
		String extend = fileNames.substring(fileNames.lastIndexOf(".") + 1);

		if (!"xls".equalsIgnoreCase(extend) && !"xlsx".equalsIgnoreCase(extend)) {// 文件格式
			json.setSuccess(false);
			json.setMsg("请选择excel格式文件上传！");
		} else if (fileSize > 1024 * 1024 * 10) {// 文件大小(2Mb)
			json.setSuccess(false);
			json.setMsg("导入文件大小不得大于10Mb！");
		} else {
			InputStream inputStream = null;
			try {
				InputStream is = new FileInputStream(f);
				// 解析xls
				List<List> list = PoiUtils.parseExcelToString(is, 6, 1, 0);
				if (!list.isEmpty()) {
					// 检查数据格式是否有错
					errorMsg = yellowPageService.findBug(cellId, list);

					if (errorMsg == null || errorMsg.equals("")) {
						// 校验成功
						List<YellowPage> yellowPages = new ArrayList<YellowPage>();
						YellowPage yellowPage = null;
						for (List item : list) {
							//插入数据到便民黄页表
							yellowPage = new YellowPage();
							
							yellowPage.setId(UniqueNumberUtils.get18UniqueNumber());
							yellowPage.setUserAccount(user.getLoginname());
							yellowPage.setSendTime(new Date());
							yellowPage.setPageName(item.get(1).toString());
							yellowPage.setCellId(cellId);
							yellowPage.setPhone0(item.get(3).toString());
							yellowPage.setPhone1(item.get(4).toString());
							yellowPage.setAddr(item.get(5).toString());
							yellowPage.setUpdateTime(new Date());
							yellowPage.setSort(Constants.SORT_DEFAULT);
							yellowPages.add(yellowPage);
						}
						
						yellowPageService.insertAll(yellowPages);
						json.setSuccess(true);
						json.setMsg("文件导入成功！");
						LogUtils.insertLog("用户导入便民黄页表格", user.getId(), request);
					} else {
						json.setSuccess(false);
						json.setMsg(errorMsg.toString());
					}
				} else {
					json.setSuccess(false);
					json.setMsg("文件数据错误！");
				}

			} catch (Exception e) {
				e.printStackTrace();
				json.setSuccess(false);
				json.setMsg("文件格式错误！");
			} finally {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException e) {
					}
				}
			}
		}

		return json;
	}

	/**
	 * @Description 将选中项置顶
	 * 
	 * @param id 主键id
	 * @param req 用户请求
	 * @return 响应结果
	 * @author liuying 1075817474@qq.com
	 * @date 2016年6月12日
	 * @see 
	 */
	@RequestMapping(value="updateSort" , method = RequestMethod.GET)
	@ResponseBody
    public RequestJson updateSort( String id, HttpServletRequest req){
        RequestJson result = new RequestJson();
        try {
        	YellowPage yellowPage = yellowPageService.selectByPrimaryKey(id);
        	if(yellowPage != null){
        		yellowPage.setUpdateTime(DateUtils.getDate());
        		yellowPageService.updateSort(yellowPage);
        	}
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("操作失败");
            result.setSuccess(false);
        }
       
        return result;
    }
}